import 'dart:io';

import 'package:dio/dio.dart';

import '../config/user_data.dart';


class DioTokenInterceptors extends Interceptor {
  @override
  Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    /// 统一参数设置
    String token = await UserData.instance.getToken() ?? "";

    String temptoken =
        "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjExYW9QdWdVTTE2S3FVRkpuOFFiIn0=.eyJpYXQiOjE3NDIyMDU5MzM0ODMsImV4cCI6MTc0MjgxMDczMzQ4Mywic3ViIjo1MDE1MDAsInJlZyI6MTc0MTE1MjY5Mjk0NywiYWlkIjoxLCJ0aXoiOiJ0aW1lem9uZSIsImluYyI6Ik1SQkRKQiJ9.MEYCIQCs070SROJdyG2nfxLGYc9KcTcPyOlvUDzHP8SbvimjqQIhAJzuuB09wcnEhxTmBHn1Im1bdRFERZT5jCAvJcfuUp2z";

    options.data ??= {};
    if (token.isNotEmpty) {
      options.headers['Authorization'] = token;
    }
    options.headers['X-TimeZone'] = "Asia/Shanghai"; //DateTime.now().timeZoneName;
    //options.headers['X-TimeZone'] = DateTime.now().timeZoneName;
    options.headers['ua_device'] = Platform.isIOS ? "ios" : "android";
    // log('请求参数=${options.queryParameters} token=$token');
    options.headers['client'] = "ios-n-${Platform.version}";
    var gps = {'lat': '30.540793159043364', 'lng': '104.05958767018807'};
    options.headers['gps'] = gps;
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    // 响应前需要做刷新token的操作
    final code = response.data['code'] ?? 0;
    if (code == 1401 || code == 403 || code == 1408) {}
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    switch (err.type) {
      // 连接服务器超时
      case DioExceptionType.connectionTimeout:
        break;
      case DioExceptionType.receiveTimeout:
        break;
      // 发送超时
      case DioExceptionType.sendTimeout:
        break;
      // 请求取消
      case DioExceptionType.cancel:
        break;
      // 404/503错误
      case DioExceptionType.badResponse:
        break;
      // other 其他错误类型
      case DioExceptionType.unknown:
        break;

      case DioExceptionType.badCertificate:
        break;
      case DioExceptionType.connectionError:
        break;
    }
    super.onError(err, handler);
  }
}
